const http = require('http')
const fs = require('fs')
const func = require('./functions')

function readFile () {
  return new Promise((resolve, reject) => {
    fs.readFile('../assets/members.json', (err, data) => {
      if (err) {
        reject(err)
      } else {
        let members = JSON.parse(data.toString())
        resolve(members)
      }
      return
    })
  })
}

function writeFile (data) {
  return new Promise((resolve, reject) => {
    fs.writeFile('../assets/members.json', JSON.stringify(data), err => {
      if (err) {
        reject(err)
      } else {
        console.log('-------------- 新增成功: ', data.phone);
        resolve()
      }
    })
  })
}

function readLogs () {
  return new Promise((resolve, reject) => {
    fs.readFile('../assets/logs.json', (err, data) => {
      if (err) {
        reject(err)
      } else {
        let members = JSON.parse(data.toString())
        resolve(members)
      }
      return
    })
  })
}

function writeLogs (data) {
  fs.writeFile('../assets/logs.json', JSON.stringify(data), err => {
    if (err) {
      console.error('-------------- 新增失败: ', data.phone, err);
    } else {
      console.log('-------------- 新增成功: ', data.phone);
    }
  })
}

function addLog (type, data) {
  readLogs().then(res => {

    if (type === 'add') {
      res[data.phone] = [data]
    } else if (type === 'update') {
      res[data.phone] ? res[data.phone].unshift(data) : (res[data.phone] = [data])
    } else if (type === 'del') {
      if (res[data.phone]) {
        if (res['deleteList']) {
          res['deleteList'].unshift({
            ...res[data.phone][res[data.phone].length - 1],
            createTime: data.createTime
          })
        } else {
          res['deleteList'] = [{
            ...res[data.phone][res[data.phone].length - 1],
            createTime: data.createTime
          }]
        }

        delete res[data.phone]
      }
    }

    writeLogs(res)
  })
}

function complete (path, query, response) {

  if (path === '/api/getList') {
    let queryObj = {
      phone: query.get('phone')
    }

    readFile().then(res => {
      let arr = []

      if (queryObj.phone) {

        for (const key in res) {
          if (Object.hasOwnProperty.call(res, key)) {
            const item = res[key];
            if (key.indexOf(queryObj.phone) >= 0) {
              arr.push(item)
            }
          }
        }

      } else {
        for (const key in res) {
          if (Object.hasOwnProperty.call(res, key)) {
            const item = res[key];
            arr.push(item)
          }
        }
      }

      response.end(formatEnd(arr))
    })

  } else if (path === '/api/add' || path === '/api/update') {
    let queryObj = {
      name: query.get('name'),
      phone: query.get('phone'),
      amount: query.get('amount'),
      direction: query.get('direction'),
      createTime: func.dateFormat()
    }

    if (!queryObj.name) {
      return response.end(formatEnd(null, '请输入名字'))
    }
    if (!queryObj.phone) {
      return response.end(formatEnd(null, '请输入手机号码'))
    }
    if (!queryObj.amount) {
      return response.end(formatEnd(null, '请输入金额'))
    }
    if (!queryObj.direction) {
      return response.end(formatEnd(null, '请选择类型'))
    }

    readFile().then(res => {
      if (path === '/api/add') {
        if (res[queryObj.phone]) {
          return response.end(formatEnd(null, '该手机号已存在'))
        } else {
          queryObj.variety = +Number(queryObj.amount)
          if (queryObj.direction == 2) {
            queryObj.amount = 0 - Number(queryObj.amount)
          } else {
            queryObj.amount = 0 + Number(queryObj.amount)
          }

          res[queryObj.phone] = queryObj

          writeFile(res).then(res => {
            addLog('add', queryObj)
            return response.end(formatEnd(queryObj))
          })
        }
      } else {

        if (res[queryObj.phone]) {
          queryObj.variety = +Number(queryObj.amount)
          if (queryObj.direction == 2) {
            queryObj.amount = Number(res[queryObj.phone].amount) - Number(queryObj.amount)
          } else {
            queryObj.amount = Number(res[queryObj.phone].amount) + Number(queryObj.amount)
          }

          res[queryObj.phone] = queryObj

          writeFile(res).then(res => {
            addLog('update', queryObj)
            return response.end(formatEnd(queryObj))
          })

        } else {
          return response.end(formatEnd(null, '该手机号不存在'))

        }
      }

    }).catch(e => {
      response.end(formatEnd())
    })
  } else if (path === '/api/del') {
    let queryObj = {
      phone: query.get('phone'),
      createTime: func.dateFormat()
    }

    if (!queryObj.phone) {
      return response.end(formatEnd(null, '请输入手机号码'))
    }

    readFile().then(res => {
      if (res[queryObj.phone]) {
        delete res[queryObj.phone]

        writeFile(res).then(res => {
          addLog('del', queryObj)
          return response.end(formatEnd(queryObj))
        })

      } else {
        return response.end(formatEnd(null, '该手机号不存在'))
      }
    })
  } else if (path === '/api/getLogList') {
    let queryObj = {
      phone: query.get('phone')
    }

    if (!queryObj.phone) {
      return response.end(formatEnd(null, '请输入手机号码'))
    }

    readLogs().then(res => {
      if (res[queryObj.phone]) {
        return response.end(formatEnd(res[queryObj.phone]))
      }

      return response.end(formatEnd([]))
    })
  }
}

function formatEnd (data, msg) {
  if (msg) {
    return JSON.stringify({
      code: 10400,
      msg
    })
  } else if (data) {
    return JSON.stringify({
      code: 10200,
      data,
    })

  } else {
    return JSON.stringify({
      code: 10500,
      msg: '操作失败'
    })
  }
}

http.createServer((request, response) => {
  let fullUrl = new URL(request.url, 'http://localhost/')
  let path = fullUrl.pathname
  let method = request.method

  if (method === 'GET') {
    if (path.indexOf('/api') === 0) {
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild");
      response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
      response.setHeader("X-Powered-By", "3.2.1");
      response.setHeader("Content-Type", "application/json;charset=utf-8");
      let query = new URLSearchParams(fullUrl.searchParams)

      complete(path, query, response)
    } else {
      if(path === '/pay' || path === '/list' || path === '/recording') {
        path = '/index.html'
      }
      fs.readFile(`dist${path}`, (err, data) => {
        if (err) {
          response.writeHead(404)
          response.end('找不到页面文件')
        } else {
          var type = path.substr(path.lastIndexOf(".") + 1, path.length)
          response.writeHead(200, { 'Content-type': "text/" + type });	//在这里设置文件类型，告诉浏览器解析方式
          response.end(data)
        }
      })
    }

  } else {

    response.end()
  }

}).listen(5293)